package com.baike.service.impl;

import com.baike.entity.Role;
import com.baike.mapper.RoleMapper;
import com.baike.mapper.RoleMenuMapper;
import com.baike.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author x_FG
 * @since 2021-10-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public boolean insertRoleInfo(Role role, Integer[] menuIds) {
        // 增加返回主键
        roleMapper.insertRole(role);
        // 获取role主键
        Integer rid = role.getRid();
        // 增加 role_menu 表
        int i = roleMenuMapper.insertRoleMenu(rid,menuIds);
        return i>0;
    }

    @Override
    public Role getRoleById(Integer id) {
        return roleMapper.selectById(id);
    }

    @Override
    public boolean updateRoleInfo(Role role, Integer[] menuIds) {
        int i=0;
        try {
            // 修改角色表
            roleMapper.updateById(role);
            // 删除中间表 role_menu
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("rid",role.getRid());
            roleMenuMapper.delete(wrapper);
            // 增加中间表 role_menu
            i = roleMenuMapper.insertRoleMenu(role.getRid(),menuIds);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return i>0;
    }

    @Override
    public boolean deleteRoleMenu(Integer id) {
        // 删除 role表
        int i = 0;
        int i1 = roleMapper.deleteById(id);
        if (i1>0){
            // 删除中间表 role_menu
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("rid",id);
            i = roleMenuMapper.delete(wrapper);
        }
        return i>0 && i1>0;
    }
}
